import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow
from tensorflow.keras.layers import *
import os
from keras.models import Sequential
import numpy as np
import keras
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import RMSprop
from sklearn.metrics import classification_report
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train=ImageDataGenerator(rescale=1/255)
validation=ImageDataGenerator(rescale=1/255)
train_dataset=train.flow_from_directory('C:/Users/21656/Desktop/Train',target_size=(224,224),batch_size=3,class_mode='binary')
Test_dataset=train.flow_from_directory('C:/Users/21656/Desktop/Test',target_size=(224,224),batch_size=3,class_mode='binary')
Found 80 images belonging to 2 classes. Found 30 images belonging to 2 classes.
Test_dataset.classes
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1])
model = Sequential()
model.add(Conv2D(16,(3,3),activation='relu',input_shape=(224,224,3)))
model.add(MaxPool2D(2,2))
model.add(Conv2D(32,(3,3),activation='relu'))
model.add(MaxPool2D(2,2))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPool2D(2,2))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 222, 222, 16) 448
max_pooling2d (MaxPooling2D (None, 111, 111, 16) 0
)
conv2d_1 (Conv2D) (None, 109, 109, 32) 4640
max_pooling2d_1 (MaxPooling (None, 54, 54, 32) 0
2D)
conv2d_2 (Conv2D) (None, 52, 52, 64) 18496
max_pooling2d_2 (MaxPooling (None, 26, 26, 64) 0
2D)
flatten (Flatten) (None, 43264) 0
dense (Dense) (None, 512) 22151680
dense_1 (Dense) (None, 1) 513
=================================================================
Total params: 22,175,777
Trainable params: 22,175,777
Non-trainable params: 0
_________________________________________________________________
opt = keras.optimizers.RMSprop(learning_rate=0.001)
model.compile(loss='binary_crossentropy',optimizer=opt ,metrics=['accuracy'])
model_fit=model.fit(train_dataset,epochs=10,validation_data=Test_dataset)
Epoch 1/10 27/27 [==============================] - 13s 429ms/step - loss: 1.9419 - accuracy: 0.5750 - val_loss: 0.3744 - val_accuracy: 0.8000 Epoch 2/10 27/27 [==============================] - 11s 410ms/step - loss: 0.5379 - accuracy: 0.8125 - val_loss: 0.7495 - val_accuracy: 0.5000 Epoch 3/10 27/27 [==============================] - 11s 409ms/step - loss: 0.6595 - accuracy: 0.7500 - val_loss: 0.1986 - val_accuracy: 0.9000 Epoch 4/10 27/27 [==============================] - 11s 398ms/step - loss: 0.5164 - accuracy: 0.8875 - val_loss: 0.2025 - val_accuracy: 0.8667 Epoch 5/10 27/27 [==============================] - 11s 397ms/step - loss: 0.3741 - accuracy: 0.9125 - val_loss: 0.1247 - val_accuracy: 0.9333 Epoch 6/10 27/27 [==============================] - 11s 402ms/step - loss: 0.2095 - accuracy: 0.9375 - val_loss: 0.5562 - val_accuracy: 0.8000 Epoch 7/10 27/27 [==============================] - 11s 397ms/step - loss: 0.5275 - accuracy: 0.9125 - val_loss: 0.2055 - val_accuracy: 0.8667 Epoch 8/10 27/27 [==============================] - 11s 397ms/step - loss: 0.2412 - accuracy: 0.9250 - val_loss: 1.4466 - val_accuracy: 0.6667 Epoch 9/10 27/27 [==============================] - 11s 388ms/step - loss: 0.0784 - accuracy: 0.9750 - val_loss: 0.2649 - val_accuracy: 0.9000 Epoch 10/10 27/27 [==============================] - 11s 398ms/step - loss: 0.5191 - accuracy: 0.9375 - val_loss: 0.1017 - val_accuracy: 0.9667
#with plots
acc = model_fit.history['accuracy']
val_acc = model_fit.history['val_accuracy']
loss = model_fit.history['loss']
val_loss = model_fit.history['val_loss']
epochs_range = range(10)
plt.figure(figsize=(15, 15))
plt.subplot(2, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
#Evaluating the result
score=model.evaluate(Test_dataset)
print(score[0])
print(score[1])
10/10 [==============================] - 1s 67ms/step - loss: 0.1017 - accuracy: 0.9667 0.10169655829668045 0.9666666388511658
validation_dataset=validation.flow_from_directory('C:/Users/21656/Desktop/Val',target_size=(224,224),batch_size=3,class_mode='binary')
dir_path="C:/Users/21656/Desktop/Val"
y_pred=[]
for i in validation_dataset.filenames:
img=image.load_img(dir_path+'//'+i,target_size=(224,224))
plt.imshow(img)
plt.show()
x=image.img_to_array(img)
x=np.expand_dims(x,axis=0)
images=np.vstack([x])
val=model.predict(images)
y_pred.append(int(val))
if val==0 :
print("Dog")
else:
print("Tree")
Found 20 images belonging to 2 classes.
1/1 [==============================] - 0s 161ms/step Dog
1/1 [==============================] - 0s 41ms/step Dog
1/1 [==============================] - 0s 38ms/step Tree
1/1 [==============================] - 0s 34ms/step Dog
1/1 [==============================] - 0s 43ms/step Tree
1/1 [==============================] - 0s 49ms/step Dog
1/1 [==============================] - 0s 34ms/step Dog
1/1 [==============================] - 0s 47ms/step Dog
1/1 [==============================] - 0s 78ms/step Tree
1/1 [==============================] - 0s 63ms/step Tree
1/1 [==============================] - 0s 42ms/step Tree
1/1 [==============================] - 0s 48ms/step Tree
1/1 [==============================] - 0s 63ms/step Tree
1/1 [==============================] - 0s 39ms/step Tree
1/1 [==============================] - 0s 47ms/step Tree
1/1 [==============================] - 0s 35ms/step Tree
1/1 [==============================] - 0s 32ms/step Tree
1/1 [==============================] - 0s 40ms/step Dog
1/1 [==============================] - 0s 58ms/step Dog
1/1 [==============================] - 0s 44ms/step Tree
print("Observerd Classes : ",validation_dataset.classes)
print("Predicted Classes : ",y_pred)
print(classification_report(y_pred,validation_dataset.classes,target_names = ['Dogs (Class 0)','Trees (Class 1)']))
Observerd Classes : [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
Predicted Classes : [0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1]
precision recall f1-score support
Dogs (Class 0) 0.70 0.78 0.74 9
Trees (Class 1) 0.80 0.73 0.76 11
accuracy 0.75 20
macro avg 0.75 0.75 0.75 20
weighted avg 0.76 0.75 0.75 20
from sklearn import metrics
confusion_matrix = metrics.confusion_matrix(validation_dataset.classes, y_pred)
cm_display = metrics.ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = range(2))
cm_display.plot()
plt.show()